<?php
namespace Home\Controller;

class AppController extends \Home\Controller\BaseController
{
	/**
	 * APP启动banner
	 * @author 尹雷
	 */
	public function startBanner()
	{
		$task = M("Task")->where(array("type_id"=>'8'))->order("create_time desc")->find();
		$fileid = explode(",",$task['file_ids'])[0];

		$file = M('File');
		$list = $this->returnList($file, array('id' => $fileid), '', 'id,name,url');

		//查询出错
		if($list === false) {
			$this->errorLog(_FILE__, __LINE__, $file->getDbError() .  '---' . $file->getError());
			$this->ajaxReturn(array('error' => 1, 'info' => '查询失败'));
		}
		
		//查询成功
		$return = $this->successResult($list);
		$this->ajaxReturn($return);
	}
	
	/**
	 * 检查APP是否有新版本
	 */
	public function checkUpdate()
	{
		//获取参数
		$param = I('params');
		$appVersion = I('data.app_version', '', '/^[1-9]+\.\d+$/', $param);
		if(!$appVersion) $this->ajaxReturn(array('error' => 1, 'info' => '请传入当前正在使用的APP版本号'));
		$platform = I('data.platform', '', '/^\d+$/', $param);
		if(!$platform) $this->ajaxReturn(array('error' => 1, 'info' => '请传入平台参数'));
		
		//构造查询条件
		$where['platform'] = $platform;
		$where['update_type'] = 1;
		$where['update_status'] = array('neq', 1);
		
		//查询版本信息
		$app = $this->returnOne('App', $where, 'app_version desc,create_time desc', 'id,app_version,file_id,platform,update_status,description');
		
		//测试代码
		//$this->ajaxReturn(array('error' => 1, 'info' => $app));
		
		if($app === false) {
			$this->errorLog(__FILE__, __LIINE__, M('App')->getDbError());
			$this->ajaxReturn(array('error' => 1, 'info' => 'APP更新检测失败'));
		}
		
		//code表示更新建议，1-查无数据，2-可选更新，3-强制更新，4-无需更新
		if(!$app) {
			$this->ajaxReturn(array('error' => 0, 'info' => array('code' => 1, 'data' => '查无数据')));
		}
		
		//判断是否需要更新
		if($appVersion < $app['app_version']) {
			$info['code'] = $app['update_status'];
			unset($app['update_status']);
			$info['data'] = $app;
		} else {
			$info['code'] = 4;
			$info['data'] = '无需更新';
		}
		
		$this->ajaxReturn(array('error' => 0, 'info' => $info));
	}
	
	/**
	 * 生成推荐码
	 * @author 尹雷
	 */
	public function recommendCode()
	{
		$data['code'] = \Common\Util\Util::randStr(8, 1);
		$data['recommendId'] = $this->user['userId'];
		$expireTime = global_config('recommend_code_expire');
		$expireTime = time() + ($expireTime ? $expireTime : 1) * 3600;
		$data['expireTime'] = $expireTime;
		$result = D('Recommend')->addRecommend($data);
		$this->ajaxReturn($result);
	}
	
	/**
	 * APP下载页面
	 * @author 尹雷
	 */
	public function index()
	{
		$param = I('params');
		//获取当前可用的App列表
		$recId = I('data.recId', '', '/^\d+$/', $param);
		
		//查询APP信息
		$field = 'id,app_version,platform,file_id';
		$apps = $this->returnList('App', array('status' => 1), $order, $field, $option);
		
		foreach($apps as $key => &$val) {
			$val['platform_name'] = C('APP_PLATFORM')[$val['platform']];
			$data = array();
			$data['apiCode'] = '_app_down_001';
			$data['param']['recId'] = $recId;
			$data['param']['appId'] = $val['id'];
			$data['token'] = api_sign($data);
			$val['json'] = json_encode($data);
		}
		
		
		//APP下载页面背景图片
		$img = $this->returnOne('File', array('file_type' => 5), 'create_time', 'id,url');
		
		$this->assign('apps', $apps);
		$this->assign('recId', $recId);
		$this->assign('imgUrl', C('FUND_DOMAIN1') . $img['url']);
		$this->display('down');
	}

	/**
	 * 下载APP
	 * @author 尹雷
	 */
	public function download()
	{
		$param = I('params');
		//获取appId
		$appId = I('data.appId', '', '/^\d+$/', $param);
		if(!$appId) $this->error('参数错误');
		
		//查询APP信息
		$app = M('App')->where(array('id' => $appId))->find();
		if(!$app) $this->error('APP信息获取失败');
		
		//获取APP文件信息
		$fileInfo = $this->returnOne('File', array('id' => $app['file_id']), '', 'id,realpath,ext');
		if(!$fileInfo) $this->error('APP文件不存在');
		
		//构造APP名称
		$fileName = $app['app_name'] . '-' . $app['app_version'];
		
		//推荐人id
		if(I('data.recId', '', '/^\d+$/', $param)) {
			$fileName .= '_' . $param['recId'];
		}
		
		//APP扩展名
		$fileName .= '.' . $fileInfo['ext'];

		$filePath = $fileInfo['realpath'];
		
		//测试代码
		//$filePath = '/home/seven/Seven/Worker/Fund/Uploads/Download/pcre2-10.20.tar.gz';
		//$fileName = 'pcre2-10.20.tar.gz';
		//die(bcdiv(filesize($filePath), 1024*1024, 2));
		
		//读取文件并输出
		if(is_file($filePath)) {
			//获取app在服务器上的路径并计算大小
			$fileSize = bcdiv(filesize($filePath), 1024*1024, 2);
			
			//服务器返回的是一个流，可以下载任何文档
			header('Content-type: application/octet-stream');
			//返回的文件的大小
			header('Content-Length: ' . filesize($filePath));
			//header('Content-Length', filesize($filePath));
			//告诉浏览器以下载方式打开文件，中文文件名需要转码
			header('Content-Disposition: attachment; filename=' . $fileName);
			$res = fopen($filePath, 'r');
			
			while(!feof($res)) {
				echo fread($res, 1024);
			}

			fclose($res);
		} else {
			$this->error('下载出错');
		}
	}

}